package edu.hubu.store.service;


import edu.hubu.store.dao.OrderDao;
import edu.hubu.store.dao.OrderItemDao;
import edu.hubu.store.dao.ProductDao;
import edu.hubu.store.domain.Order;
import edu.hubu.store.domain.OrderItem;
import edu.hubu.store.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class OrderService {
    @Autowired
    private OrderItemDao oidao;
    @Autowired
    private OrderDao odao;
    @Autowired
    private ProductDao pdao;

    // 1.添加订单
    public void addOrder(Order order) {
        // 1.开启事务
        //            DataSourceUtils.startTransaction();
        // 2.完成操作
        // 2.1向orders表中添加数据
        odao.addProduct(order);
        // 2.2向orderItem表中添加数据
        for (OrderItem item : order.getOrderItems()) {
            oidao.addOrderItem(item);
            // 2.3修改商品表中数据.
            pdao.changeProductNum(item);
        }
    }

    // 根据用户查找订单
    public List<Order> findOrderByUser(User user) {
        return odao.findOrderByUser(user);
    }

    // 根据id查找订单
    public Order findOrderById(String id) {
        Order order = odao.findOrderById(id);
        List<OrderItem> items = oidao.findOrderItemByOrder(order);
        order.setOrderItems(items);
        return order;
    }

    // 查找所有订单
    public List<Order> findAllOrder() {
        return odao.findAllOrder();
    }

    // 支付成功后修改订单状态
    public void updateState(String id) {
        odao.updateOrderState(id);
    }

    // 多条件查询订单信息
    public List<Order> findOrderByManyCondition(String id, String receiverName) {
        return odao.findOrderByManyCondition(id, receiverName);
    }

    //根据id删除订单 管理员删除订单
    public void delOrderById(String id) {
        oidao.delOrderItems(id);
        odao.delOrderById(id);
    }

    //普通用户删除订单
    public void delOrderByIdWithClient(String id) {
        //从订单项中查找商品购买数量
        Order order = new Order();
        order.setId(id);
        List<OrderItem> items = oidao.findOrderItemByOrder(order);
        //修改商品数量
        for (OrderItem item : items) {
            pdao.updateProductNum(item);
        }
        oidao.delOrderItems(id); //删除订单项
        odao.delOrderById(id); //删除订单
    }
}
